import { isArray, isObject } from '@/utils/is'
const APP_NAME = import.meta.env.VITE_APP_NAME

export const userStorage = () => {
	const getStorage = (key : string, sync : boolean = true) => {
		let storage = ''
		if (sync) {
			try {
				storage = uni.getStorageSync(`${APP_NAME}_${key}`);
				if (storage) {
					return storage
				}
			} catch (e) { }
		} else {
			uni.getStorage({
				key: `${APP_NAME}_${key}`,
				success: function (res) {
					storage = res.data
				}
			});
			return storage
		}
	}
	const setStorage = (key : string, value : any, sync : boolean = true) => {
		if (sync) {
			uni.setStorageSync(`${APP_NAME}_${key}`, isArray(value) || isObject(value) ? JSON.stringify(value) : value);
		} else {
			uni.setStorage({
				key: `${APP_NAME}_${key}`,
				data: isArray(value) || isObject(value) ? JSON.stringify(value) : value,
				success: function () {
					console.log('setStorage success');
				}
			});
		}
	}
	const removeStorage = (key : string, sync : boolean = true) => {
		if (sync) {
			uni.removeStorageSync(`${APP_NAME}_${key}`);
		} else {
			uni.removeStorage({
				key: `${APP_NAME}_${key}`,
				success: function () {
					console.log('removeStorage success');
				}
			});
		}
	}
	const clearStorage = (sync : boolean = true) => {
		if (sync) {
			uni.clearStorageSync();
		} else {
			uni.clearStorage();
		}
	}

	return {
		getStorage,
		setStorage,
		removeStorage,
		clearStorage
	}
}